/*
 * @Author: doramart 
 * @Date: 2019-11-20 14:24:07 
 * @Description 发布更新主题
 * @Last Modified by: doramart
 * @Last Modified time: 2020-11-06 23:32:12
 */
const fs = require('fs');
const path = require('path');
var distPath = path.resolve(__dirname, '../dist/');
var themesPath = path.resolve(__dirname, '../app/view/');
var assetsPath = path.resolve(__dirname, '../app/assets/');
var themesDistPath = path.resolve(__dirname, '../app/public/themes/');
var shell = require('shelljs');
const archiver = require('archiver')

const targetPulishFolder = distPath + '/systemThemes';
const {
    scanforder,
    uploadByQiniu
} = require('../backstage/build/utils');

// 指定打包模块
let designatedModule = ['qingyulan', 'hidora'];

let copyType = "dev",
    targetModules = ''; //  ALL 或 separate 可选
let argvs = process.argv;
if (argvs[2] == '--type') {
    copyType = argvs[3];
}
if (argvs[4] == '--modules') {
    targetModules = argvs[5];
    if (targetModules && targetModules != 'ALL') {
        if (targetModules.indexOf(',') >= 0 && targetModules.split(',').length > 0) {
            designatedModule = designatedModule.concat(targetModules.split(','));
        } else {
            designatedModule.push(targetModules);
        }
        console.log('begin build target module: ', targetModules);
    }
}

let targetBuildModules = scanforder(themesDistPath);
if (designatedModule.length > 0) {
    targetBuildModules = designatedModule;
}


if (fs.existsSync(`${targetPulishFolder}`)) {
    shell.rm('-rf', `${targetPulishFolder}/*`);
} else {
    shell.mkdir('-p', `${targetPulishFolder}`);
}


targetBuildModules.forEach(async function (name) {
    if (name != 'manage' && name != 'users') {
        shell.cd(`${themesPath}/${name}`);
        shell.mkdir('-p', `${targetPulishFolder}/${name}/assets`);

        let cpStr = `rsync -av --exclude "node_modules" ${assetsPath}/${name}/* ${targetPulishFolder}/${name}/assets`;
        shell.exec(cpStr);
        shell.cp('-R', `${themesPath}/${name}/*`, `${targetPulishFolder}/${name}`);
        if (fs.existsSync(`${targetPulishFolder}/${name}/dist`)) {
            shell.rm('-rf', `${targetPulishFolder}/${name}/dist`);
        }
        shell.mkdir('-p', `${targetPulishFolder}/${name}/dist`);
        shell.cp('-R', `${themesDistPath}/${name}/*`, `${targetPulishFolder}/${name}/dist`);

        let doArchive = () => {
            return new Promise((resolve, reject) => {
                let output = fs.createWriteStream(`${targetPulishFolder}/${name}.zip`);
                let archive = archiver('zip');

                output.on('close', async () => {
                    console.log('archiver themes success');
                    resolve();
                });

                output.on('end', function (ctx, app) {
                    console.log('Data has been drained');
                });

                archive.on('error', function (err) {
                    throw err;
                });

                archive.pipe(output);
                archive.directory(`${targetPulishFolder}/${name}`, false);
                archive.finalize();
            })
        }
        await doArchive();

        shell.rm('-rf', `${targetPulishFolder}/${name}`);

    }
});

// 上传到七牛
if (copyType == 'prd') {

    let uploadInfo = [];

    let updateQniu = async (uploadInfo) => {
        console.log('Begin upload to Qiniu');
        for (const uploadItem of uploadInfo) {
            let {
                localFile,
                pathKey
            } = uploadItem;
            console.log(`Begin upload ${pathKey}`);
            await uploadByQiniu(localFile, 'cms/sql-templates/' + pathKey);
            console.log(`Upload ${pathKey} success!`);
        }
        console.log('All upload to Qiniu success!');
    }

    // console.log('--targetBuildModules--', targetBuildModules);
    for (const moduleItem of targetBuildModules) {
        uploadInfo = [{
            localFile: `${targetPulishFolder}/${moduleItem}.zip`,
            pathKey: `2.1.7/${moduleItem}.zip`
        }];
        updateQniu(uploadInfo);
    }

}